package websocket.util;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author nieruijie
 * @date 2022/5/10 21:16
 */
public class DigitalTrans {
    /**
     * 数字字符串转ASCII码字符串
     *
     * @return ASCII字符串
     */
    public static String StringToAsciiString(String content) {
        String result = "";
        int max = content.length();
        for (int i = 0; i < max; i++) {
            char c = content.charAt(i);
            String b = Integer.toHexString(c);
            result = result + b;
        }
        return result;
    }

    /**
     * 十六进制转字符串
     *
     * @param hexString  十六进制字符串
     * @param encodeType 编码类型4：Unicode，2：普通编码
     * @return 字符串
     */
    public static String hexStringToString(String hexString, int encodeType) {
        String result = "";
        int max = hexString.length() / encodeType;
        for (int i = 0; i < max; i++) {
            char c = (char) DigitalTrans.hexStringToAlgorism(hexString.substring(i * encodeType, (i + 1) * encodeType));
            result += c;
        }
        return result;
    }

    public static String covert16Zhuan10(String content) {
        BigDecimal number = new BigDecimal(0);
        String[] HighLetter = {"A", "B", "C", "D", "E", "F"};
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i <= 9; i++) {
            map.put(i + "", i);
        }
        for (int j = 10; j < HighLetter.length + 10; j++) {
            map.put(HighLetter[j - 10], j);
        }
        String[] str = new String[content.length()];
        for (int i = 0; i < str.length; i++) {
            str[i] = content.substring(i, i + 1);
        }
        for (int i = 0; i < str.length; i++) {
            number = number.add(new BigDecimal(map.get(str[i]) * Math.pow(16, str.length - 1 - i)));
        }
        return number.toString();
    }

    public static Long covert16Zhuan10ToLong(String content) {
        BigDecimal number = new BigDecimal(0);
        String[] HighLetter = {"A", "B", "C", "D", "E", "F"};
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i <= 9; i++) {
            map.put(i + "", i);
        }
        for (int j = 10; j < HighLetter.length + 10; j++) {
            map.put(HighLetter[j - 10], j);
        }
        String[] str = new String[content.length()];
        for (int i = 0; i < str.length; i++) {
            str[i] = content.substring(i, i + 1);
        }
        for (int i = 0; i < str.length; i++) {
            number = number.add(new BigDecimal(map.get(str[i]) * Math.pow(16, str.length - 1 - i)));
        }
        return Long.valueOf(number.toString());
    }

    /**
     * 十六进制数据处理  （四字节）
     * 低字节在前，高字节在后
     *
     * @param a1 字节1
     * @param a2 字节2
     * @param a3 字节3
     * @param a4 字节4
     * @return 结果
     */
    public static int read16Data(String a1, String a2, String a3, String a4) {
        return (0xff000000 & (Integer.valueOf(a1, 16).byteValue() << 24))
                | (0xff0000 & (Integer.valueOf(a2, 16).byteValue() << 16))
                | (0xff00 & (Integer.valueOf(a3, 16).byteValue() << 8))
                | (0xff & Integer.valueOf(a4, 16).byteValue());
    }

    /**
     * 读取十六进制的某一个字节的8位bit
     * @param a1
     * @return
     */
    public static int[] read8Bit(String a1) {
        int[] resultData = new int[2];
        // 取出第0位 内环使能
        int stu1 = Integer.valueOf(a1, 16).byteValue() & 0x01;
        resultData[0] = stu1;
        System.err.println(stu1);
        // 取出第4位 外环使能
        int stu2 = ((Integer.valueOf(a1, 16).byteValue() & 0x10) >> 4);
        resultData[1] = stu2;
        System.err.println(stu2);

//        int stu1 = Integer.valueOf(a1, 16).byteValue() & 0x04;
//        System.err.println(stu1);
//        int stu2 = (Integer.valueOf(a1, 16).byteValue() & 0x40 >> 4);
//        System.err.println(stu2);

        return resultData;
    }

//    stu1=Rec_Buffer[11]&0x0f;
//    stu2=((Rec_Buffer[11]&0xf0)>>4);
//    m_nenable.SetCheck(stu1&0x01);
//    m_wenable.SetCheck(stu2&0x01);
//
//    if((stu1&0x04)==0x04)
//
//    {
//        m_bx.SetWindowText("ÄÚ»·ÒÑÎÈ¶¨");
//    }
//    else
//
//    {
//        m_bx.SetWindowText("ÄÚ»·Î´ÎÈ¶¨");
//    }
//
//     if((stu2&0x04)==0x04)
//
//    {
//        m_by.SetWindowText("Íâ»·ÒÑÎÈ¶¨");
//    }
//    else
//
//    {
//        m_by.SetWindowText("Íâ»·Î´ÎÈ¶¨");
//    }

    /**
     * 十六进制字符串装十进制
     *
     * @param hex 十六进制字符串
     * @return 十进制数值
     */
    public static int hexStringToAlgorism(String hex) {
        hex = hex.toUpperCase();
        int max = hex.length();
        int result = 0;
        for (int i = max; i > 0; i--) {
            char c = hex.charAt(i - 1);
            int algorism = 0;
            if (c >= '0' && c <= '9') {
                algorism = c - '0';
            } else {
                algorism = c - 55;
            }
            result += Math.pow(16, max - i) * algorism;
        }
        return result;
    }

    /**
     * 十六转二进制
     *
     * @param hex 十六进制字符串
     * @return 二进制字符串
     */
    public static String hexStringToBinary(String hex) {
        hex = hex.toUpperCase();
        String result = "";
        int max = hex.length();
        for (int i = 0; i < max; i++) {
            char c = hex.charAt(i);
            switch (c) {
                case '0':
                    result += "0000";
                    break;
                case '1':
                    result += "0001";
                    break;
                case '2':
                    result += "0010";
                    break;
                case '3':
                    result += "0011";
                    break;
                case '4':
                    result += "0100";
                    break;
                case '5':
                    result += "0101";
                    break;
                case '6':
                    result += "0110";
                    break;
                case '7':
                    result += "0111";
                    break;
                case '8':
                    result += "1000";
                    break;
                case '9':
                    result += "1001";
                    break;
                case 'A':
                    result += "1010";
                    break;
                case 'B':
                    result += "1011";
                    break;
                case 'C':
                    result += "1100";
                    break;
                case 'D':
                    result += "1101";
                    break;
                case 'E':
                    result += "1110";
                    break;
                case 'F':
                    result += "1111";
                    break;
            }
        }
        return result;
    }

    /**
     * ASCII码字符串转数字字符串
     *
     * @return 字符串
     */
    public static String AsciiStringToString(String content) {
        String result = "";
        int length = content.length() / 2;
        for (int i = 0; i < length; i++) {
            String c = content.substring(i * 2, i * 2 + 2);
            int a = hexStringToAlgorism(c);
            char b = (char) a;
            String d = String.valueOf(b);
            result += d;
        }
        return result;
    }

    /**
     * 将十进制转换为指定长度的十六进制字符串
     *
     * @param algorism  int 十进制数字
     * @param maxLength int 转换后的十六进制字符串长度
     * @return String 转换后的十六进制字符串
     */
    public static String algorismToHEXString(int algorism, int maxLength) {
        String result = "";
        result = Integer.toHexString(algorism);

        if (result.length() % 2 == 1) {
            result = "0" + result;
        }
        return patchHexString(result.toUpperCase(), maxLength);
    }

    /**
     * 字节数组转为普通字符串（ASCII对应的字符）
     *
     * @param bytearray byte[]
     * @return String
     */
    public static String bytetoString(byte[] bytearray) {
        String result = "";
        char temp;

        int length = bytearray.length;
        for (int i = 0; i < length; i++) {
            temp = (char) bytearray[i];
            result += temp;
        }
        return result;
    }

    /**
     * 二进制字符串转十进制
     *
     * @param binary 二进制字符串
     * @return 十进制数值
     */
    public static int binaryToAlgorism(String binary) {
        int max = binary.length();
        int result = 0;
        for (int i = max; i > 0; i--) {
            char c = binary.charAt(i - 1);
            int algorism = c - '0';
            result += Math.pow(2, max - i) * algorism;
        }
        return result;
    }

    /**
     * 十进制转换为十六进制字符串
     *
     * @param algorism int 十进制的数字
     * @return String 对应的十六进制字符串
     */
    public static String algorismToHEXString(int algorism) {
        String result = "";
        result = Integer.toHexString(algorism);

        if (result.length() % 2 == 1) {
            result = "0" + result;

        }
        result = result.toUpperCase();

        return result;
    }

    /**
     * HEX字符串前补0，主要用于长度位数不足。
     *
     * @param str       String 需要补充长度的十六进制字符串
     * @param maxLength int 补充后十六进制字符串的长度
     * @return 补充结果
     */
    static public String patchHexString(String str, int maxLength) {
        String temp = "";
        for (int i = 0; i < maxLength - str.length(); i++) {
            temp = "0" + temp;
        }
        str = (temp + str).substring(0, maxLength);
        return str;
    }

    /**
     * 将一个字符串转换为int
     *
     * @param s          String 要转换的字符串
     * @param defaultInt int 如果出现异常,默认返回的数字
     * @param radix      int 要转换的字符串是什么进制的,如16 8 10.
     * @return int 转换后的数字
     */
    public static int parseToInt(String s, int defaultInt, int radix) {
        int i = 0;
        try {
            i = Integer.parseInt(s, radix);
        } catch (NumberFormatException ex) {
            i = defaultInt;
        }
        return i;
    }

    /**
     * 将一个十进制形式的数字字符串转换为int
     *
     * @param s          String 要转换的字符串
     * @param defaultInt int 如果出现异常,默认返回的数字
     * @return int 转换后的数字
     */
    public static int parseToInt(String s, int defaultInt) {
        int i = 0;
        try {
            i = Integer.parseInt(s);
        } catch (NumberFormatException ex) {
            i = defaultInt;
        }
        return i;
    }

    /**
     * 十六进制字符串转为Byte数组,每两个十六进制字符转为一个Byte
     *
     * @param hex 十六进制字符串
     * @return byte 转换结果
     */
    public static byte[] hexStringToByte(String hex) {
        int max = hex.length() / 2;
        byte[] bytes = new byte[max];
        String binarys = DigitalTrans.hexStringToBinary(hex);
        for (int i = 0; i < max; i++) {
            bytes[i] = (byte) DigitalTrans.binaryToAlgorism(binarys.substring(i * 8 + 1, (i + 1) * 8));
            if (binarys.charAt(8 * i) == '1') {
                bytes[i] = (byte) (0 - bytes[i]);
            }
        }
        return bytes;
    }

    /**
     * 十六进制串转化为byte数组
     *
     * @return the array of byte
     */
    public static final byte[] hex2byte(String hex) throws IllegalArgumentException {
        if (hex.length() % 2 != 0) {
            throw new IllegalArgumentException();
        }
        char[] arr = hex.toCharArray();
        byte[] b = new byte[hex.length() / 2];
        for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
            String swap = "" + arr[i++] + arr[i];
            int byteint = Integer.parseInt(swap, 16) & 0xFF;
            b[j] = new Integer(byteint).byteValue();
        }
        return b;
    }

    /**
     * 字节数组转换为十六进制字符串
     *
     * @param b byte[] 需要转换的字节数组
     * @return String 十六进制字符串
     */
    public static final String byte2hex(byte b[]) {
        if (b == null) {
            throw new IllegalArgumentException("Argument b ( byte array ) is null! ");
        }
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xff);
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }


    // 字节数组转字符串
    public static String printHexString(byte[] b) {
        StringBuffer sbf = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sbf.append(hex.toUpperCase() + " ");
        }
        return sbf.toString().trim();
    }

    /**
     * 16进制转换成为string类型字符串
     *
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }


    public static String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {
            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }

    public static String convertHexToString2(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }

    /**
     * 去除十六进制数据空格
     * 例如：AA 44 12 1C 2A 00 00
     * AA44121C2A0000
     *
     * @param hex 　十六进制数据
     * @return
     */
    public static String convertHexToStringAndTrim(String hex) {
        return hex.replaceAll(" ", "");
    }

    private static final char HexCharArr[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 字节数组转化为十六进制字符串
     *
     * @param content 字节数组
     * @return 十六进制字符串
     */
    public static String byteArrToHex(byte[] content) {
        char[] strArr = new char[content.length * 2];
        int i = 0;
        for (byte bt : content) {
            strArr[i++] = HexCharArr[bt >>> 4 & 0xf];
            strArr[i++] = HexCharArr[bt & 0xf];
        }
        return new String(strArr);
    }

    public static String bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += hex.toUpperCase();
        }
        return ret;
    }

    private static char[] map = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String toHex(int num) {
        int count = 8;
        if (num == 0) return "0";
        String result = "";
        while (num != 0) {
            int x = num & 0xF;
            if (count % 2 == 0) {
                result = map[(x)] + " " + result;
            } else {
                result = map[(x)] + result;
            }
            num = (num >>> 4);
            count--;
        }
        return result.toUpperCase();
    }

    /**
     * 保留最后两位并去除空格
     *
     * @param num
     * @return
     */
    public static String toHex2Trim(int num) {
        String hex = toHex(num).trim();
        if (hex.length() == 1) return "0" + hex;
        if (hex.length() == 11) return hex;
        hex = hex.substring(hex.length() - 2);
        return hex;
    }

    /**
     * 反转的时候需要高字节在前，低字节在后
     * 例如：FF FE 03 04
     * 转成：04 03 FE FF
     *
     * @return
     */
    public static String toHexFanZhuan(String hex) {
        String[] hexArr = hex.split(" ");

        String[] resultArr = new String[hexArr.length];
        int num = 0;
        for (int i = hexArr.length; i > 0; i--) {
            resultArr[num] = hexArr[i - 1];
            num++;
        }
        String resultStr = "";
        for (int i = 0; i < resultArr.length; i++) {
            resultStr += " " + resultArr[i];
        }
        return resultStr.trim();
    }

    /**
     * 本方法用于转台数据发送使用转换
     *
     * @param num
     * @return
     */
    public static String toHex3buWei(int num) {
        // 数字转成16进制
        String hex = toHex(num).trim();
        // (04 03 FE FF十一位)
        if (hex.length() == 11) {
            // 反转的时候需要高字节在前，低字节在后
            return toHexFanZhuan(hex);
        }
        // 去除空格
        String replaceHex = hex.replace(" ", "");
        // 获取去除空格后的长度
        int replaceHexLength = replaceHex.length();
        // 去除空格后补满是八位长度0403FEFF
        String qianZhui = "";
        for (int i = 0; i < 8 - replaceHexLength; i++) {
            qianZhui += "0";
        }
        String resultStr = qianZhui + replaceHex;
        resultStr = resultStr.replaceAll("(.{2})", "$1 ").trim();
        return resultStr;
    }

    public static void main(String[] args) {

//        System.err.println(DigitalTrans.covert16Zhuan10("AA A5 15"));
//        System.err.println(DigitalTrans.covert16Zhuan10("A5"));
//        System.err.println(DigitalTrans.covert16Zhuan10("55"));
//        System.err.println(DigitalTrans.covert16Zhuan10("0F"));
//        System.err.println(DigitalTrans.read16Data("FF","D8","F0","21"));
//        System.err.println(DigitalTrans.toHex(-130300));
//        System.err.println(DigitalTrans.byte2hex("-130300".getBytes()));
//        System.err.println(DigitalTrans.bytes2HexString("131884".getBytes()));
        read8Bit("7F");
//        System.err.println(DigitalTrans.toHex3buWei(-130300));

    }

}
